package com.springboot.demo.service.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.springboot.demo.dao.UserDOMapper;
import com.springboot.demo.dao.UserPasswordDOMapper;
import com.springboot.demo.dataobject.UserDO;
import com.springboot.demo.dataobject.UserPasswordDO;
import com.springboot.demo.service.UserService;
import com.springboot.demo.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutionException;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDOMapper userDOMapper;
    @Autowired
    private UserPasswordDOMapper userPasswordDOMapper;

    @Override
    // CaffeineConfig 注解
    @Cacheable(value="users", key="#user.id")
    public UserModel getUserById(Integer id) throws ExecutionException {
        UserDO userDO = userDOMapper.selectByPrimaryKey(id);
        if (userDO == null) {
            return null;
        }
        //through userid to get pwd
        UserPasswordDO upd = userPasswordDOMapper.selectByUserId(id);
        UserModel um = convertFromDataObject(userDO, upd);
        return um;
    }

    private UserModel convertFromDataObject(UserDO userDO, UserPasswordDO userPasswordDO) {
        if (userDO == null) {
            return null;
        }
        UserModel userModel = new UserModel();
        BeanUtils.copyProperties(userDO, userModel);
        if (userPasswordDO != null) {
            userModel.setEncrptPassword(userPasswordDO.getEncrptPassword());
        }
        return userModel;

    }
}
